package com.shimmer;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.List;

/**
 * @Package com.shimmer
 * @Author shimmer
 * @Date 2020/8/16 9:43
 * @TODO
 */
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fileName = null;
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            // 设置文件上传大小：1M
            factory.setSizeThreshold(1024*1024);
            
            List items = null;
            try {
                items = fileUpload.parseRequest(req);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iterator = items.iterator();
            while (iterator.hasNext()){
                FileItem item = (FileItem) iterator.next();
                //  当item.isFormField返回true的时候，就表示是常规字段,false为文件。
                if (!item.isFormField()){
                    // 根据时间来命名图片
                    fileName = System.currentTimeMillis()+".jpg";
                    // 通过getRealPath获取上传文件夹
                    String realPath = req.getServletContext().getRealPath("uploaded");
                    File file = new File(realPath, fileName);
                    file.getParentFile().mkdir();
                    
                    // 通过item.getInputStream()获取浏览器上传的文件的输入流
                    InputStream is = item.getInputStream();
                    
                    //复制文件
                    FileOutputStream os = new FileOutputStream(file);
                    byte[] bytes = new byte[1024 * 1024];
                    int length = 0;
                    while (-1!=(length=is.read(bytes))){
                        os.write(bytes,0,length);
                    }
                    os.close();
                    is.close();
                }else {
                    System.out.println(item.getFieldName());
                    String value = item.getString();
                    value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
                    System.out.println(value);
                }
            }
            String html = "<img width='200' height='150' src='uploaded/%s'/>";
            resp.setContentType("text/html");
            PrintWriter pw= resp.getWriter();

            pw.format(html, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
